import DatePicker from "components/antd-compatible/date-picker";
import React from 'react';
import { connect } from 'react-redux';
import { Modal, Button, Checkbox, message, Form, Radio,  Spin, Icon, Carousel } from 'antd';

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
import 'styles/home.scss';
import { formatNumber, messages, deepFullCopy } from "share/common";
import { ImageUpload } from 'components/index';
import DAService from 'containers/dashboard-admin.service';
import BaseService from 'share/base.service';
import config from 'config';
import menuRoute from 'routes/menuRoute';
import LogoImg from 'images/logo.png';
import BankImg from 'images/home/bank.png';
import CameraImg from 'images/home/camera.png';
import InvoiceImg from 'images/home/invoice.png';
import QRCodeImg from 'images/home/QRCode.jpg';
import BannerImg from 'images/home/banner.jpg';
import BannerEnImg from 'images/home/banner_en.jpg';
import AMapBannerImg from 'images/ad-img/a-map/banner.jpg';
import AMapBannerEnImg from 'images/ad-img/a-map/banner_en.jpg';
import moment from 'moment';
import homeService from 'containers/home.service'
import Chart from "components/echarts";
import InPageStopAnnouncement from 'components/template/in-page-stop-announcement/in-page-stop-announcement';
import updateLogService from "containers/help-center-user/update-log/update-log.service";
const { MonthPicker } = DatePicker;
import UpdateRenewal from 'components/template/dingding/update-renewal.js'
import FullScreen from 'components/full-screen';
import AdHuaBei from 'containers/advertisement-page/ad-hua-bei';
import AdAMap from 'containers/advertisement-page/ad-a-map';
import { withRouter } from 'react-router'
/**
 *
 * @param title
 * @param content
 * @param warning
 * @param showLeftColor 是否显示标签左侧渐变边框
 * @returns {*}
 */
function infoItemFactory({ title, content, warning, showLeftColor }) {
  let className = ['info-item-wrapper'];
  if (showLeftColor) {
    className.push('left-color');
  }
  return (
    <div className={className.join(' ')}>
      <div className="info-item-title">
        {title}
      </div>
      <div className="info-item-content">
        {content}
      </div>
      {warning && <div className="info-item-warning">
        {warning}
      </div>}
    </div>
  )
}

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsShow: false,
      uploadedImages: [],//已经上传的logo
      showCustomLogo: false,//是否显示自定义的logo
      userAgreementIsEnabled: false,
      userAgreementUrl: menuRoute.getRouteItem('user-agreement') ? menuRoute.getRouteItem('user-agreement').url : null,
      remainedDay: 0,
      cardData: {},
      supportedLanguages: deepFullCopy(props.tenant.tenantLanguageDTO && props.tenant.tenantLanguageDTO.supportedLanguages || []),
      defaultLanguage: props.tenant.tenantLanguageDTO && props.tenant.tenantLanguageDTO.defaultLanguage || {},
      currentMonth: moment(new Date()),
      bodyData: {},
      isFetchingBodyData: false,
      renewVisible: false,
      judgeLog: false, // 是否 判断 更新日志内容高度
      logs: [], //更新日志
      showAdvertisement: false, //是否展示广告 0522广告：花呗
      showAdvertisementAMap: false, //是否展示广告 0814广告：高德
    }
    this.serviceList = [
      {
        icon: CameraImg,
        key: "OCR",
        title: messages('basic-1.key1')/*拍照识别*/,
        description: messages('basic-1.key2')/*通过拍照，系统自动识别出发票信息填入单据*/
      },
      {
        icon: InvoiceImg,
        key: "CHECK_INVOICE",
        title: messages('basic-1.key3')/*发票查验*/,
        description: messages('basic-1.key4')/*扫描发票二维码，获取来自国家税务局的发票核对结果*/
      },
      {
        icon: BankImg,
        key: "BWE",
        title: messages('basic-1.key5')/*银企直联*/,
        description: messages('basic-1.key6')/*对接银行系统，便捷管理银行账户、转账支付等*/
      },
    ]
  }

  componentWillMount() {
    this.daysRemaining();
    this.getData();
    this.getBodyData();
    this.getUpdateLogList();
    // 监听浏览器点击返回 (目的 是 打开花呗广告 按浏览器返回键 不会从首页跳走)
    this.props.router.setRouteLeaveHook(
      this.props.route,
      this.routerWillLeave
    )
  };

  routerWillLeave = (nextLocation) => {
    if (this.state.showAdvertisement || this.state.showAdvertisementAMap) {
      this.setState({showAdvertisement: false, showAdvertisementAMap: false})
      return false
    }
  };

  componentDidMount() {
    this.getTenantInfo()
  };

  getData = () => {
    homeService.getData()
      .then((res) => {
        this.setState({ cardData: res.data })
      }).catch()
  };

  getBodyData = () => {
    let { currentMonth } = this.state;

    if (currentMonth) {
      currentMonth = currentMonth.format('YYYY-MM')
    }
    return homeService.getHomeBodyData(currentMonth)
      .then((res) => {
        this.setState({ bodyData: res.data })
      })
  };

  getTenantInfo = () => {
    DAService.getUserAgreementByTenantId()
      .then((res) => {
        let data = res.data;
        this.setState({
          userAgreementIsEnabled: data.enabled,
        })
      })
  };

  getUpdateLogList = () => {
    updateLogService.getUpdateLogList({size: 1}).then(res => {
      this.setState({
        logs: res.data
      }, ()=>{
        this.setState({judgeLog: true})
      })
    })
  };

  setLogoImages = () => {
    let uploadedImages = [];
    let uploadedImage = this.getUploadedImage(this.props.tenant);
    if (uploadedImage) {
      uploadedImages = [uploadedImage]
    }
    this.setState({
      uploadedImages,
      showCustomLogo: this.props.tenant.showCustomLogo ? this.props.tenant.showCustomLogo : false
    })
  };
  getUploadedImage = (data) => {
    let uploadedImage = null;
    if (data.logoURL) {
      uploadedImage = {};
      uploadedImage.iconURL = data.logoURL;
      uploadedImage.fileURL = data.logoURL;
      uploadedImage.thumbnailUrl = data.logoURL;
      uploadedImage.attachmentOID = "logo";
      uploadedImage.fileName = `logo.${data.logoURL.split('/logo/')[1].split('?')[0].split('.')[1] || 'png'}`;
    }
    return uploadedImage;
  };
  showSetModal = () => {
    let { tenant } = this.props;
    let defaultLanguage = tenant.tenantLanguageDTO ? tenant.tenantLanguageDTO.defaultLanguage : {};
    let supportedLanguages = deepFullCopy(tenant.tenantLanguageDTO ? tenant.tenantLanguageDTO.supportedLanguages : []);
    this.setState({
      supportedLanguages,
      defaultLanguage,
      modalIsShow: true,
    }, () => {
      this.setLogoImages()
    })
  };
  hideSetModal = () => {
    this.setState({
      modalIsShow: false,
    })
  };
  setConfirm = () => {
    let uploadedImages = this.state.uploadedImages;
    const { defaultLanguage, supportedLanguages } = this.state;
    if (supportedLanguages.every(item => !item.enabled)) {
      message.error(messages('basic-1.key7')/*请选择企业支持语言*/);
      return;
    }
    if (!defaultLanguage.code) {
      message.error(messages('basic-1.key8')/*请选择企业默认语言*/);
      return;
    }
    if (uploadedImages.length === 0) {
      DAService.deleteImgId(this.props.tenant.id)
        .then((res) => {
          // 接口设置了租户特性
          // 重新设置一个 redux 控制全局的一些特性
          BaseService.getTenant(this.props.tenant.id);
        })
    }
    let data = {
      tenantId: this.props.tenant.id,
      showCustomLogo: this.state.showCustomLogo,
      tenantLanguageDTO: { defaultLanguage, supportedLanguages, }
    };
    DAService.updateTenantInfo(data)
      .then((res) => {
        // 接口设置了租户特性
        // 重新设置一个 redux 控制全局的一些特性
        BaseService.getTenant(res.data.id);
        this.setState({
          modalIsShow: false,
        })
      })
  };
  //是否用自定义logo
  onImageUseChange = (e) => {
    this.setState({
      showCustomLogo: e.target.checked
    })
  };

  //上传图片后的回调函数
  handleUploadImageChange = (fileList) => {
    fileList.map(item => {
      item.attachmentOID = item.id;
      item.status = 'done';
      item.fileURL = item.logoURL;
      item.fileName = `logo.${item.logoURL.split('/logo/')[1].split('?')[0].split('.')[1] || 'png'}`;
    });
    this.setState({
      uploadedImages: fileList
    })
  };

  //查看用户协议
  goUserAgreement = () => {
    this.context.router.push(this.state.userAgreementUrl)
  };

  validDate = () => {
    const { tenant } = this.props;
    let content = messages('basic-1.key9',{arg1: tenant.trialExpiredDate?tenant.trialRemainDays:messages('dashboard.key263')/*无期限*/})/*购买的服务剩余{arg1}天，请联系客服*/;
    Modal.warning({
      title: <div dangerouslySetInnerHTML={{ __html: content }}/>,
      content: '400 829 7878',
    });
  };

  invalidDate = () => {
    Modal.warning({
      title: messages('basic-1.key10')/*购买的服务已到期，请联系客服*/,
      content: '400 829 7878',
    });
  };

  daysRemaining = () => {
    const { tenant } = this.props;
    let startArr = moment(tenant.createdDate).format('YYYY-MM-DD').split("-");
    let endArr = moment(new Date()).format('YYYY-MM-DD').split("-");
    let startDate = new Date(startArr[0], startArr[1], startArr[2]);
    let endDate = new Date(endArr[0], endArr[1], endArr[2]);
    let days = (endDate - startDate) / (24 * 60 * 60 * 1000);
    this.setState({
      remainedDay: days,
    })
  };

  onRadioGroupChange = (e) => {
    const { supportedLanguages } = this.state;
    if (e.target.checked) {
      supportedLanguages.forEach(item => {
        if (item.code === e.target.value) {
          this.setState({
            defaultLanguage: item,
          })
        }
      });
    }
  };

  goOrderOnline = (key) => {
    let url = menuRoute.getPageUrlByKey("senior-service-open").replace(":serviceType", key);
    this.context.router.push(url);
  };

  goOrderManagement = (key) => {
    let url = menuRoute.getPageUrlByKey("order-management").replace(":orderType", key);
    this.context.router.push(url);
  };

  onCheckboxChange = (e) => {
    const { supportedLanguages, defaultLanguage } = this.state;
    supportedLanguages.forEach(item => {
      if (item.code === e.target.value) {
        item.enabled = e.target.checked;
      }
      if (e.target.value === defaultLanguage.code && !e.target.checked) {
        this.setState({
          defaultLanguage: {},
        })
      }
    });
    this.setState({
      supportedLanguages,
    });
  };

  onMonthChange = (currentMonth) => {
    let { isFetchingBodyData } = this.state;
    if (isFetchingBodyData) {
      message.warning(messages('basic-1.key11')/*正在加载，请稍等...*/);
      return
    }
    if (currentMonth) {
      isFetchingBodyData = true;
    }
    this.setState({
      currentMonth,
      isFetchingBodyData
    }, () => {
      this.getBodyData().then(() => {
        this.setState({
          isFetchingBodyData: false
        })
      })
    })
  };

  renderPersonData = () => {
    let { cardData } = this.state;
    let { language } = this.props;
    let {
      activityCount,
      totalCount,
      licensedCount,
      licenseUsedRate,
      licenseWarnDate,
      activityStatistics,
      licenseStatistics,
    } = cardData;
    let pieOptions = homeService.createOptions({
      data: licenseUsedRate,
      type: 'pie',
      config: {
        title: messages('basic-1.key12')/*License已使用*/
      }
    });
    let barOptions = homeService.createOptions({
      data: activityStatistics,
      type: 'bar'
    });
    let lineOptions = homeService.createOptions({
      data: licenseStatistics,
      type: 'line'
    });
    if (licenseWarnDate) {
      licenseWarnDate = moment(licenseWarnDate).format('YYYY-MM')
    }
    const overviewList = [{
      title: messages('basic-1.key13')/*员工总数(人)*/,
      value: formatNumber(totalCount)
    }, {
      title: messages('basic-1.key14')/*已激活用户(人)*/,
      value: formatNumber(activityCount)
    }, {
      title: messages('basic-1.key15')/*License上限(个)*/,
      value: formatNumber(licensedCount),
      warning: licenseWarnDate ? messages('basic-1.key16',{arg1: licenseWarnDate})/*预计 {arg1} 可用余量将不足*/ : undefined
    }];
    const chartsList = [pieOptions, barOptions, lineOptions];
    return (
      <div className="card-wrapper">
        <div className="card-head">
          <div className="card-head-title">
            {messages('basic-1.key17')/*人员数据*/}
          </div>
        </div>
        <div className="card-content-wrapper">
          <div className="overview-wrapper" style={{height: language.code === 'it_IT' ? '90px' : "80px" }}>
            {overviewList.map(item => (
              <div className="overview-item">
                <div className="overview-title">
                  {item.title}
                </div>
                <div className="overview-value">
                  {item.value}
                </div>
                {item.warning && <div className="overview-warning">
                  {item.warning}
                </div>}
              </div>
            ))}
          </div>
          <div className="flex-wrapper">
            {chartsList.map(option => (
              <div className="card-chart">
                <Chart options={option}
                       height={288}/>
              </div>
            ))}
          </div>
        </div>
      </div>
    )
  };

  renderMonthData = () => {
    let { isFetchingBodyData } = this.state;
    return (
      <Spin spinning={isFetchingBodyData}>
        {this.renderDocData()}
        {this.renderPayService()}
        {this.renderVendorData()}
      </Spin>
    )
  };

  renderDocData = () => {
    let { currentMonth, bodyData } = this.state;

    let {
      submitApplicationBillMonthlyQty,
      approvedApplicationBillMonthlyQty,
      submitExpenseReportMonthlyQty,
      approvedExpenseReportMonthlyQty,
      submitLoanBillMonthlyQty,
      approvedLoanBillMonthlyQty,
    } = bodyData;

    const cardsList = [{
      title: messages('basic-1.key18')/*申请单*/,
      submitted: formatNumber(submitApplicationBillMonthlyQty),
      statements: formatNumber(approvedApplicationBillMonthlyQty),
    }, {
      title: messages('basic-1.key19')/*报销单*/,
      submitted: formatNumber(submitExpenseReportMonthlyQty),
      statements: formatNumber(approvedExpenseReportMonthlyQty),
    }, {
      title: messages('basic-1.key20')/*借款单*/,
      submitted: formatNumber(submitLoanBillMonthlyQty),
      statements: formatNumber(approvedLoanBillMonthlyQty),
    }];

    return (
      <div className="card-wrapper">
        <div className="card-head">
          <div className="card-head-title">
            {messages('basic-1.key21')/*单据信息*/}
          </div>
          <div className="card-head-util">
            <MonthPicker
              disabledDate={current => current && (current.valueOf() > Date.now() || current.valueOf() < Date.now() - 31536000000)}
              style={{ width: '100%' }}
              onChange={this.onMonthChange}
              allowClear={true}
              value={currentMonth}
              defaultValue={moment()}/>
          </div>
        </div>

        <div className="flex-wrapper">
          {cardsList.map(item => (
            <div className="sub-card-wrapper">
              <div className="sub-card-head">
                <div className="sub-card-head-title">
                  {item.title}
                </div>
              </div>
              <div className="infos-wrapper">
                {infoItemFactory({ title: messages('basic-1.key22')/*提交量(单)*/, content: item.submitted })}
                {infoItemFactory({ title: messages('basic-1.key23')/*结单量(单)*/, content: item.statements })}
              </div>
            </div>
          ))}
        </div>
      </div>
    )
  };

  renderPayService = () => {
    const { isDingTalkEnv } = this.props;
    let { bodyData } = this.state;
    let {
      checkInvoiceRemainQty,
      checkInvoiceUsedMonthlyQty,
      checkInvoiceWarnDate,
      ocrRemainQty,
      ocrUsedMonthlyQty,
      ocrWarnDate,
      bweAvailableQty,
      bweAvailableMonthlyQty
    } = bodyData;

    if (checkInvoiceWarnDate) {
      checkInvoiceWarnDate = moment(checkInvoiceWarnDate).format('YYYY-MM')
    }

    if (ocrWarnDate) {
      ocrWarnDate = moment(ocrWarnDate).format('YYYY-MM')
    }

    const cardsList = [{
      title: messages('basic-1.key1')/*拍照识别*/,
      used: formatNumber(ocrUsedMonthlyQty),
      remained: formatNumber(ocrRemainQty),
      firstSubTitle: messages('basic-1.key24')/*使用量(次)*/,
      warning: checkInvoiceWarnDate ? messages('basic-1.key16',{arg1: ocrWarnDate})/*预计 {arg1} 可用余量将不足*/ : undefined,
      key: 'OCR'
    }, {
      title: messages('basic-1.key3')/*发票查验*/,
      used: formatNumber(checkInvoiceUsedMonthlyQty),
      remained: formatNumber(checkInvoiceRemainQty),
      firstSubTitle: messages('basic-1.key24')/*使用量(次)*/,
      warning: checkInvoiceWarnDate ? messages('basic-1.key16',{arg1: checkInvoiceWarnDate})/*预计 {arg1} 可用余量将不足*/ : undefined,
      key: 'CHECK_INVOICE'
    }, {
      title: messages('basic-1.key5')/*银企直联*/,
      used: formatNumber(bweAvailableMonthlyQty),
      remained: formatNumber(bweAvailableQty),
      firstSubTitle: messages('basic-1.key25')/*对接账户(个)*/,
      key: 'BWE'
    }];
    return (
      <div className="flex-wrapper">
        {cardsList.map(item => (
          <div className="sub-card-wrapper card-wrapper">
            <div className="sub-card-head">
              <div className="sub-card-head-title">
                {item.title}
              </div>
              <div className="sub-card-href"
                   onClick={() => this.goOrderManagement(item.key)}>
                {messages('basic-1.key26')/*查看订单*/}
              </div>
            </div>
            <div className="infos-wrapper">
              {infoItemFactory({ title: item.firstSubTitle, content: item.used, showLeftColor: true })}
              {infoItemFactory({
                title: messages('basic-1.key27')/*可用余量(次)*/,
                content: item.remained,
                warning: item.warning,
                showLeftColor: true
              })}
            </div>
          </div>
        ))}
      </div>
    )
  };

  renderVendorData = () => {
    let { bodyData } = this.state;
    let {
      airTicketMasterSupplier,
      airTicketUsedMonthlyQty,
      hotelMasterSupplier,
      hotelUsedMonthlyQty,
      trainMasterSupplier,
      trainUsedMonthlyQty,
      carMasterSupplier,
      carUsedMonthlyQty
    } = bodyData;

    const cardsList = [{
      title: messages('basic-1.key28')/*机票*/,
      used: formatNumber(airTicketUsedMonthlyQty),
      usedTitle: messages('basic-1.key29')/*出票(张)*/,
      vendor: airTicketMasterSupplier || '-',
    }, {
      title: messages('basic-1.key30')/*酒店*/,
      used: formatNumber(hotelUsedMonthlyQty),
      usedTitle: messages('basic-1.key31')/*用量(间*夜)*/,
      vendor: hotelMasterSupplier || '-',
    }, {
      title: messages('basic-1.key32')/*火车*/,
      used: formatNumber(trainUsedMonthlyQty),
      usedTitle: messages('basic-1.key29')/*出票(张)*/,
      vendor: trainMasterSupplier || '-',
    }, {
      title: messages('basic-1.key33')/*用车*/,
      used: formatNumber(carUsedMonthlyQty),
      usedTitle: messages('basic-1.key34')/*用量(次)*/,
      vendor: carMasterSupplier || '-',
    }];
    return (
      <div className="flex-wrapper">
        {cardsList.map(item => (
          <div className="sub-card-wrapper card-wrapper">
            <div className="sub-card-head">
              <div className="sub-card-head-title">
                {item.title}
              </div>
            </div>
            <div className="infos-wrapper">
              {infoItemFactory({ title: item.usedTitle, content: item.used, showLeftColor: true })}
              {infoItemFactory({
                title: messages('basic-1.key35')/*主要供应商*/,
                content: item.vendor,
                showLeftColor: true
              })}
            </div>
          </div>
        ))}
      </div>
    )
  };

  goPurchaseHistory = () => {
    this.context.router.push("/main/purchase-history");
  };

  goUpdateLog = () => {
    window.open(`${window.ISIE9 ? "#" : ""}${menuRoute.getRouteItem('update-log','key').url}`, '_blank');
  };

  renderExtraService = () => {
    const { isDingTalkEnv } = this.props;
    return (
      <div className="extra-service card-wrapper">
        <div className="head-wrapper card-head" style={{padding: '0 20px'}}>
          <div className="card-head-title side-title">{messages('basic-1.key36')/*增值服务*/}</div>
          <div className="href" onClick={() => this.goOrderManagement('all')}>
            {messages('common.more')/*更多*/}
          </div>
        </div>
        <div className="card-content-wrapper" style={{padding: '20px'}}>
          {this.serviceList.map((item)=> {
            return <div className="single-service">
              <div className="header-info">
                <div>
                  <img className="img" src={item.icon}/>
                  <span className="service-title">{item.title}</span>
                </div>
                {!(isDingTalkEnv && sessionStorage.getItem('isDingTalkSSO') === 'true') &&
                <div className="href" onClick={() => this.goOrderOnline(item.key)}>
                  {messages('basic-1.key37')/*购买*/}
                </div>}
              </div>
              <div className="description">
                {item.description}
              </div>
            </div>
          })}
        </div>
      </div>
    )
  }

  renderHeliosWeChat = () => {
    return (
      <div className="helios-wechat card-wrapper">
        <div className="head-wrapper card-head" style={{padding: '0 20px'}}>
          <div className="card-head-title side-title">{messages('basic-1.key38')/*微信扫码关注*/}</div>
        </div>
        <div className="card-content-wrapper content" style={{padding: '20px'}}>
          <div className="description">
            {messages('basic-1.key39')/*扫码关注Helios公众号，了解最新产品动态，更有干货分享和优惠活动等你哟*/}
          </div>
          <img className="img" src={QRCodeImg}/>
        </div>
      </div>
    )
  }

  renderHeliosUpdateLog = () => {
    const { logs, judgeLog } = this.state;
    return (
      <div className="helios-update-log card-wrapper">
        <div className="head-wrapper card-head" style={{padding: '0 20px'}}>
          <div className="card-head-title side-title">{messages('basic-1.key40')/*更新日志*/}</div>
          <div className="href" onClick={this.goUpdateLog}>{messages('common.more')/*更多*/}</div>
        </div>
        <div className="card-content-wrapper content" style={{padding: '20px'}}>
          {logs.length ?
            <div style={{minHeight: '270px', maxHeight: '620px', overFlow: 'hidden'}}>
              <p className="version">{messages('basic-1.key41')/*版本*/ + '：' + logs[0].version}</p>
              <div style={{maxHeight: '540px', overflow: 'hidden'}}>
                <p
                  className="log"
                  ref={ref => this.updateLogRef = ref}
                  dangerouslySetInnerHTML={{
                    __html: logs[0].content.replace(/style="color.*?;/g, 'style="color: #6C788C;').replace(/style="font-size:.*?;/g, 'style="font-size: 12px;')
                  }}
                />
              </div>
              {judgeLog && this.updateLogRef && this.updateLogRef.clientHeight > 540 && <p style={{marginTop: '-8px'}}>......</p>}
            </div>
            :
            <p>{messages('basic-1.key42')/*当前暂无更新日志*/}</p>
          }
        </div>
      </div>
    )
  }

  render() {
    const { tenant, isDingTalkEnv, language } = this.props;
    const { modalIsShow, supportedLanguages, defaultLanguage, renewVisible, showAdvertisement, showAdvertisementAMap } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16, offset: 1 },
    };
    let qrLink = "https://h5.dingtalk.com/appcenter/detail.html?showmenu=false&dd_share=false&goodsCode=DD_GOODS-101001047305&corpId="
      + sessionStorage.getItem('corpId');
    return (
      <div className="home background-transparent" style={{padding: 0}}>
        <div className="helios-page-header">
          {/*运维公告*/}
          <InPageStopAnnouncement/>
          <div className="left">
            <div className="img-wrap">
              {tenant.logoURL ? <img src={tenant.logoURL}/> : <img src={LogoImg}/>}
            </div>
            <div className="company-content">
              <div className="company-line">
                <div className="company-name">{tenant.tenantName}</div>
              </div>
              <div className="company-detail">
                <span>
                  {
                    tenant.createdDate ?
                      `${messages('basic-1.key43')/*创建时间*/}: ${new Date(tenant.createdDate).format('yyyy-MM-dd')}`
                      : null
                  }
                </span>
                {
                  !isDingTalkEnv && tenant.licenseType === "TRIAL" && tenant.expireControlMode === "1" &&
                  <span>
                    {
                      tenant.status === "TRAIL" &&
                      <span className="company-probation company-probation-valid"
                            onClick={this.validDate}>
                        {
                          tenant.trialExpiredDate ?
                            messages('basic-1.key44',{arg1: tenant.trialRemainDays})/*剩余试用期{arg1}天*/
                            : messages('basic-1.key45')/*使用无期限*/
                        }
                        &nbsp;<div className='triangle'/>&nbsp;
                     </span>
                    }
                    {
                      tenant.status === "TRIAL_EXPIRED" &&
                      <span className="company-probation company-probation-invalid"
                            onClick={this.invalidDate}>
                      {messages('basic-1.key46')/*试用期已到期*/}&nbsp;
                        <div className='triangle'/>
                        &nbsp;
                      </span>
                    }
                  </span>
                }
              </div>
            </div>
            <div className="edit-button-group">
              <div className="page-change-url" onClick={() => {this.context.router.push("/main/dashboard")}}>
                <Icon type="swap" /><span>&nbsp;{messages('basic-1.key47')/*切换到个人首页*/}</span>
              </div>
              <div className="page-change-url" onClick={this.showSetModal}>
                <Icon type="edit" /><span>&nbsp;{messages('basic-1.key48')/*编辑企业信息*/}</span>
              </div>
            </div>
            {
              isDingTalkEnv && tenant.licenseType !== 'TEST' &&
              <div className="trial-content-area">
                <div className="f-left trial-text">
                  {
                    tenant.licenseType === 'REAL' ?
                      tenant.trialExpiredDate ?
                        <div>
                          <span className="f-right trial-block company-probation-valid"/>
                          <span className="f-right">
                        {messages('basic-1.key49')/*剩余有效期*/}&nbsp;
                            {tenant.trialRemainDays}
                            {messages('basic-1.key50')/*天*/}
                      </span>
                          <div className="clear"/>
                        </div>
                        :
                      <div>
                        <span className="f-right trial-block company-probation-invalid"/>
                        <span className="f-right">{messages('basic-1.key51')/*服务已到期*/}</span>
                        <div className="clear"/>
                      </div>
                      :
                      tenant.status === "TRAIL" ?
                      <div>
                        <span className="f-right trial-block company-probation-valid"/>
                        <span className="f-right">
                          {
                            tenant.trialExpiredDate ?
                              messages('basic-1.key44',{arg1: tenant.trialRemainDays})/*剩余试用期{arg1}天*/
                              : messages('basic-1.key45')/*使用无期限*/
                          }
                      </span>
                        <div className="clear"/>
                      </div>
                        :
                        tenant.status === "TRIAL_EXPIRED" &&
                        <div>
                          <span className="f-right trial-block company-probation-invalid"/>
                          <span className="f-right">{messages('basic-1.key51')/*服务已到期*/}</span>
                          <div className="clear"/>
                        </div>
                  }
                <div className="trial-date">
                  {messages('basic-1.key52')/*到期时间：*/}
                  {tenant.trialExpiredDate ? moment(tenant.trialExpiredDate).format("YYYY-MM-DD") : "-"}
                </div>
                </div>
                <div className="f-right">
                  <div className="fake-button renew-button" onClick={() => {this.setState({renewVisible: true})}}>
                    {messages('basic-1.key53')/*续费*/}
                  </div>
                  <div className="fake-button purchase-history-button" onClick={this.goPurchaseHistory}>{messages('basic-1.key54')/*购买记录*/}</div>
                </div>
                <div className="clear"/>
              </div>
            }
          </div>
        </div>

        <div className="helios-page-content">
          <div className="helios-page-body">
            {this.renderPersonData()}
            {this.renderMonthData()}
          </div>

          <div className="helios-page-slider">
            <div className="ad-box">
              <Carousel autoplay dots>
                <div className='single-ad-box'>
                  <img onMouseDown={e => e.preventDefault()} className="img" src={language.code === 'zh_cn' ? AMapBannerImg : AMapBannerEnImg}/>
                  {
                    language.code === 'zh_cn' &&
                    <div className="touch-area-a-map" onClick={()=>{this.setState({showAdvertisementAMap: true})}} />
                  }
                </div>
                <div className='single-ad-box'>
                  <img onMouseDown={e => e.preventDefault()} className="img" src={language.code === 'zh_cn' ? BannerImg : BannerEnImg}/>
                  {
                    language.code === 'zh_cn' &&
                    <div className="touch-area-hua-bei" onClick={()=>{this.setState({showAdvertisement: true})}} />
                  }
                </div>
              </Carousel>
            </div>
            {this.renderExtraService()}
            {this.renderHeliosWeChat()}
            {this.renderHeliosUpdateLog()}
          </div>
        </div>

        <Modal
          title={messages('basic-1.key48')/*编辑企业信息*/}
          width={600}
          onCancel={this.hideSetModal}
          visible={modalIsShow}
          onOk={this.setConfirm}
        >
          <Form>
            <FormItem {...formItemLayout} label={messages('basic-1.key55')/*企业名*/}>
              <div style={{ fontSize: 16, fontWeight: 500 }}>{tenant.tenantName}</div>
            </FormItem>
            <FormItem {...formItemLayout} label={messages('basic-1.key56')/*企业LOGO*/}>
              <div className="img-wrap">
                <ImageUpload
                  uploadUrl={config.baseUrl + "/api/tenant/upload/logo/" + tenant.id}
                  attachmentType="INVOICE_IMAGES"
                  fileType={["PNG", 'png', 'JEPG', 'jepg', 'jpg', 'JPG', 'bmp', 'BMP', "jpg", "JPG", "jpeg", "JPEG"]}
                  defaultFileList={this.state.uploadedImages}
                  onChange={this.handleUploadImageChange}
                  maxNum={1}/>
              </div>
              <div className="img-tips" style={{ color: "#999", fontSize: 13 }}>
                {messages('basic-1.key57')/*建议上传图片尺寸为390*390，大小不超过2M*/}
              </div>
              <div>
                <Checkbox checked={this.state.showCustomLogo} onChange={this.onImageUseChange}>
                  {this.props.isDingTalkEnv ?
                    messages('basic-1.key58')/*在PC端显示该logo*/:
                    messages('basic-1.key59')/*在APP启动页及PC端显示该logo*/}
                </Checkbox>
              </div>
            </FormItem>
            {
              supportedLanguages.length ?
                <FormItem {...formItemLayout} label={
                  <span><span style={{ color: "red" }}>*</span>&nbsp;{messages('basic-1.key60')/*企业支持语言*/}</span>}>
                  {
                    supportedLanguages.map(item => {
                      return (
                        <Checkbox value={item.code} onChange={this.onCheckboxChange}
                                  checked={item.enabled}>{item.name}</Checkbox>
                      )
                    })
                  }
                </FormItem>
                : null
            }
            {
              supportedLanguages.length ?
                <FormItem {...formItemLayout}
                          label={<span><span
                            style={{ color: "red" }}>*</span>&nbsp;{messages('basic-1.key61')/*企业默认语言*/}</span>}>
                  <RadioGroup onChange={this.onRadioGroupChange} value={defaultLanguage.code}>
                    {
                      supportedLanguages.map(item => {
                        return (
                          <Radio value={item.code} disabled={!item.enabled}>
                            {item.name}
                          </Radio>
                        )
                      })
                    }
                  </RadioGroup>
                  <div className="img-tips" style={{ color: "#999", fontSize: 13 }}>
                    {messages('basic-1.key62')/*企业默认语言必须是企业所支持语言*/}
                  </div>
                </FormItem>
                : null
            }
          </Form>
          <div>
          </div>
        </Modal>
        {renewVisible && <UpdateRenewal visible={renewVisible} onClose={()=>{this.setState({renewVisible: false})}}/>}
        {showAdvertisement &&
        <FullScreen animateIn="fadeIn" animateOut="fadeOut" style={{ background: '#FFFFFF' }}>
          <AdHuaBei onCancel={()=>{this.setState({showAdvertisement: false})}} />
        </FullScreen>}
        {showAdvertisementAMap &&
        <FullScreen animateIn="fadeIn" animateOut="fadeOut" style={{ background: '#FFFFFF' }}>
          <AdAMap onCancel={()=>{this.setState({showAdvertisementAMap: false})}} />
        </FullScreen>}
      </div>
    );
  }
}

Home.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    language: state.main.language,
    tenant: state.login.tenant,
    isOldCompany: state.login.isOldCompany,
    menuTree: state.login.menuTree,
    isDingTalkEnv: state.main.isDingTalkEnv
  }
}

const wrappedHome = Form.create()(Home);
export default withRouter(connect(mapStateToProps)(wrappedHome));
